#include "mainwindow.h"
#include <QMessageBox>

MainWindow::MainWindow(QWidget *parent)
    : QWidget(parent)
    , m_timer(new QTimer(this))
    , m_isDarkTheme(false)
    , m_showSeconds(true)
    , m_user24Hour(false)
    , m_alarmEnabled(false)
    , m_showPanel(false)
	, m_settings(QSettings::NativeFormat, QSettings::UserScope, "QtClock", "ClockWidget")
{
    ui.setupUi(this);

    setWindowTitle(tr("qt clock"));
    setMinimumSize(400, 300);
    resize(600, 500);

    setupUI();
    loadSettings();

	connect(m_timer, &QTimer::timeout, this, &MainWindow::updateTime);
    m_timer->start(1000);

    updateTime();
}

MainWindow::~MainWindow()
{
    saveSettings();
}

void MainWindow::updateTime()
{
    m_currentTime = QDateTime::currentDateTime();
	ui.widgetClockAnalog->setTime(m_currentTime);
    ui.widgetClockDigital->setTime(m_currentTime);
	QString status = QString("%1%2").arg(tr("current time : "))
		.arg(m_currentTime.toString("yyyy-MM-dd hh:mm:ss"));
    if (m_alarmEnabled)
        status += QString(" | %1%2").arg("clock : ").arg(m_alarmTime.toString("hh:mm"));
	ui.labelStatus->setText(status);
    if (m_alarmEnabled && m_currentTime.time().hour() == m_alarmTime.hour()
        && m_currentTime.time().minute() == m_alarmTime.minute()
        && m_currentTime.time().second() == 0)
        onAlarmTriggered();

}

void MainWindow::toggleClockMode()
{
    int currentIndex = ui.stackedWidget->currentIndex();
	int nextIndex = (currentIndex + 1) % ui.stackedWidget->count();
    ui.stackedWidget->setCurrentIndex(nextIndex);

	ui.buttonMode->setText(nextIndex == 0 ? tr("Analog Clock") : tr("Digital Clock"));
}

void MainWindow::toggleTheme()
{
	m_isDarkTheme = !m_isDarkTheme;

    QString themeStyle;
    if (m_isDarkTheme)
    {
        themeStyle = "QWidget { background-color: #2b2b2b; color: #ffffff; }"
            "QPushButton { background-color: #404040; border: 1px solid #606060; padding: 5px; }"
            "QPushButton:hover { background-color: #505050; }"
            "QGroupBox { font-weight: bold; border: 2px solid #606060; margin: 5px; }"
            "QGroupBox::title { subcontrol-origin: margin; left: 10px; padding: 0 5px 0 5px; }";
		ui.buttonTheme->setText(tr("Dark Theme"));
    }
    else
    {
        // themeStyle = "";
		ui.buttonTheme->setText(tr("Light Theme"));
    }
	setStyleSheet(themeStyle);
	ui.widgetClockAnalog->setDarkTheme(m_isDarkTheme);
	ui.widgetClockDigital->setDarkTheme(m_isDarkTheme);
}

void MainWindow::onAlarmTriggered()
{
	QMessageBox::information(this, tr("Alarm Triggered"),
		tr("The alarm has been triggered at %1").arg(m_alarmTime.toString("hh:mm")));
	// QSound::play(":/sounds/alarm.wav");
}

void MainWindow::onSettingsChanged()
{
    m_showSeconds = ui.checkShowSecond->isChecked();
	m_user24Hour = ui.checkUse24Hour->isChecked();
	m_alarmEnabled = ui.checkAlarmEnable->isChecked();
	m_alarmTime = ui.timeAlarm->time();

	ui.timeAlarm->setEnabled(m_alarmEnabled);
	ui.widgetClockAnalog->setShowSeconds(m_showSeconds);
	ui.widgetClockDigital->setShowSeconds(m_showSeconds);
	ui.widgetClockDigital->setUse24Hour(m_user24Hour);
}

void MainWindow::updatePanel(bool check)
{
	m_showPanel = check;
	ui.buttonShowPanel->setChecked(check);
	static const QString showText[] = { tr("Show Panel"), tr("Hide Panel") };
	ui.buttonShowPanel->setText(showText[m_showPanel]);
	for (const auto& group : findChildren<QGroupBox*>())
	{
		group->setVisible(m_showPanel);
	}
}

void MainWindow::setupUI()
{
    setupMenuBar();
    setupSettingsPanel();
}

void MainWindow::setupMenuBar()
{
	connect(ui.buttonMode, &QPushButton::clicked, this, &MainWindow::toggleClockMode);
	connect(ui.buttonTheme, &QPushButton::clicked, this, &MainWindow::toggleTheme);
}

void MainWindow::setupSettingsPanel()
{
	connect(ui.checkShowSecond, &QCheckBox::toggled, this, &MainWindow::onSettingsChanged);
	connect(ui.checkUse24Hour, &QCheckBox::toggled, this, &MainWindow::onSettingsChanged);
	ui.checkAlarmEnable->setChecked(m_alarmEnabled);
	connect(ui.checkAlarmEnable, &QCheckBox::toggled, this, &MainWindow::onSettingsChanged);
	ui.timeAlarm->setEnabled(m_alarmEnabled);
	connect(ui.timeAlarm, &QTimeEdit::timeChanged, this, &MainWindow::onSettingsChanged);
	connect(ui.sliderOpacity, &QSlider::valueChanged, 
        this, [this](int value)
        {
			setWindowOpacity(value / 100.0);
        }
    );
	connect(ui.buttonShowPanel, &QPushButton::toggled, this, &MainWindow::updatePanel);
	updatePanel(false);
}

void MainWindow::loadSettings()
{
    m_settings.beginGroup("clock_settings");

	m_isDarkTheme = m_settings.value("dark_theme", false).toBool();
	m_showSeconds = m_settings.value("show_seconds", true).toBool();
	m_user24Hour = m_settings.value("user_24_hour", false).toBool();
	m_alarmEnabled = m_settings.value("alarm_enabled", false).toBool();
	m_alarmTime = m_settings.value("alarm_time", QTime(12, 0)).toTime();
	m_showPanel = m_settings.value("show_panel", false).toBool();

	m_isDarkTheme = !m_isDarkTheme; 
	toggleTheme();

    onSettingsChanged();
}

void MainWindow::saveSettings()
{
	m_settings.setValue("dark_theme", m_isDarkTheme);
	m_settings.setValue("show_seconds", m_showSeconds);
	m_settings.setValue("user_24_hour", m_user24Hour);
	m_settings.setValue("alarm_enabled", m_alarmEnabled);
	m_settings.setValue("alarm_time", m_alarmTime);
	m_settings.setValue("show_panel", m_showPanel);

	m_settings.endGroup();
}
